<?php

require_once('admincontroller.php');

class Faqs extends AdminController
{
	function Faqs()
	{
		parent::AdminController();
		$this->load->model('Faq');
		$this->main_navigation = 'site';
		$this->sub_navigation = 'faq';
	}

	function index()
	{
		$data['faqs'] = $this->Faq->all();
		$this->display('faq_list', $data);
	}

	function sort()
	{
		$data['faqs'] = $this->Faq->all();
		$this->display('faq_sort', $data);
	}

	function update_positions()
	{
		$position = 1;
		foreach ($_POST['faq'] as $faq_id) {
			$faq = $this->Faq->plain_get($faq_id);
			if ($faq->position != $position) {
				$faq->position = $position;
				if (!$this->Faq->save($faq)) {
					$this->output->set_status_header(400);
				break;
				}
			}
			++$position;
		}
	}

	function new_faq()
	{
		$data['faq'] = new Faq();
		$this->display('faq_new', $data);
	}

	function edit($id)
	{
		$data['faq'] = $this->Faq->plain_get($id);
		$this->display('faq_edit', $data);
	}

	function create()
	{
		$faq = new Faq();
		$faq->creator_id = $faq->updater_id = $this->session->userdata('user_id');
		$faq->created_at = $faq->updated_at = date_db_format();
		$faq->position = $this->Faq->get_next_position();

		$errors = $this->Faq->set_data($faq, $_POST);

		if (count($errors) == 0 && $this->Faq->save($faq)) {
			$data['success_notice'] = 'Question créée !';
			$data['faqs'] = $this->Faq->all();
			$this->display('faq_list', $data);
		}
		else {
			$data['error_notice'] = $errors;
			$data['faq'] = $faq;
			$this->display('faq_new', $data);
		}
	}

	function update($id)
	{
		$faq = $this->Faq->plain_get($id, false);
		$faq->updater_id = $this->session->userdata('user_id');
		$faq->updated_at = date_db_format();

		$errors = $this->Faq->set_data($faq, $_POST);

		if (count($errors) == 0 && $this->Faq->save($faq)) {
			$data['success_notice'] = 'Question mise à jour !';
			$data['faqs'] = $this->Faq->all();
			$this->display('faq_list', $data);
		}
		else {
			$data['error_notice'] = $errors;
			$data['faq'] = $faq;
			$this->display('faq_edit', $data);
		}
	}

	function delete($id)
	{
		if (!$this->Faq->delete($id)) {
			$this->output->set_status_header(400);
		}
	}

	function restore($id)
	{
		if ($this->Faq->restore($id)) {
			$data['success_notice'] = 'Suppression de la question annulée';
		}
		else {
			$data['error_notice'] = 'Impossible de restaurer la question';
		}
		$data['faqs'] = $this->Faq->all();
		$this->display('faq_list', $data);
	}

	function details($id)
	{
		$data['faq'] = $this->Faq->get_by_id($id);
		$this->load->view('admin/faqs/faq_details', $data);
	}
}
